package com.dwxt.cdms.service;

import cn.hutool.core.io.resource.BytesResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.EcgDataMapper;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.EcgData;
import com.dwxt.cdms.entity.vo.EcgDataVO;
import com.dwxt.cdms.util.EcgUtil;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.HttpUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EcgService {


    @Autowired
    private CustomerService customerService;

    @Autowired
    private EcgDataMapper ecgDataMapper;

    @Autowired
    private StationService stationService;


    /**
     * @Description: 上传分析心电贴数据
     * @param map:
     * @return com.dwxt.common.base.BaseResult
     * @author chendq
     * @date 2021/10/18
     */
    public BaseResult uploadEcgData(Map map) {
        Integer customerId = (Integer) map.get("customerId");
        String ecgStr = (String) map.get("ecgData");
        //不生成文件方式
        BytesResource bytesResource = EcgUtil.Ecg2BytesResource(ecgStr);
        HashMap<String, Object> formMap = new HashMap<>();
        String ecgToken = RedisUtil.get("ecgToken", String.class);
        if (ecgToken == null || "".equals(ecgToken)) {
            ecgToken = getToken();
        }
        Customer customer = customerService.selectCustomerById(customerId);
        formMap.put("token", ecgToken);
        formMap.put("height", customer.getHeight());
        formMap.put("weight", customer.getWeight());
        formMap.put("age", customer.getAge());
        formMap.put("gender", customer.getSex());
        formMap.put("fs", 150);
        formMap.put("gainK", 3466);
        formMap.put("ecFile", bytesResource);
        HttpResponse execute = HttpRequest
                .post("http://203.195.168.139:8086/amsuAnalysis/file-service/41c0df02b438ddaa47a2/uploadMovementData")
                .form(formMap)
                .execute();
        String body = execute.body();
        try {
            JSONObject jsonObject = JSON.parseObject(body);
            Object ret = jsonObject.get("ret");

            //心电贴分析失败
            if (!ObjectUtils.equals("200", ret)) {
                log.error("心电贴数据分析失败！请求数据:" + formMap.toString() + ",返回数据：" + body);
                return BaseResult.build(StatusCode.ANALYSE_FAIL);
            }

            EcgDataVO vo = JSON.parseObject(jsonObject.getJSONObject("errDesc").toJSONString(), EcgDataVO.class);
            EcgData ecgData = VO2Entity(vo);
            ecgData.setCustomerId(customerId);
            int i = ecgDataMapper.insertSelective(ecgData);
            return BaseResult.ok(i);
        } catch (JSONException e) {
            log.error("心电贴数据分析失败！请求数据:" + formMap.toString() + ",返回数据：" + body);
            return BaseResult.build(StatusCode.ANALYSE_FAIL);
        }
    }


    public EcgData VO2Entity(EcgDataVO vo) {
        EcgData entity = new EcgData();
        BeanUtils.copyProperties(vo, entity);
        entity.setApbPoslistStr(vo.getApbPoslist() == null ? "" : vo.getApbPoslist().toString());
        entity.setPvcPoslistStr(vo.getPvcPoslist() == null ? "" : vo.getPvcPoslist().toString());
        entity.setArrestPoslistStr(vo.getArrestPoslist() == null ? "" : vo.getArrestPoslist().toString());
        entity.setMissedPoslistStr(vo.getMissedPoslist() == null ? "" : vo.getMissedPoslist().toString());
        entity.setInsertPvcPoslistStr(vo.getInsertPvcPoslist() == null ? "" : vo.getInsertPvcPoslist().toString());
        entity.setVtPoslistStr(vo.getVtPoslist() == null ? "" : vo.getVtPoslist().toString());
        entity.setBigeminyPoslistStr(vo.getBigeminyPoslist() == null ? "" : vo.getBigeminyPoslist().toString());
        entity.setTrigeminyPoslistStr(vo.getTrigeminyPoslist() == null ? "" : vo.getTrigeminyPoslist().toString());
        entity.setRListStr(vo.getRList() == null ? "" : vo.getRList().toString());
        return entity;
    }

    public EcgDataVO entity2VO(EcgData ecg) {
        EcgDataVO vo = new EcgDataVO();
        BeanUtils.copyProperties(ecg, vo);
        vo.setApbPoslist(JSON.parseArray(ecg.getApbPoslistStr()));
        vo.setPvcPoslist(JSON.parseArray(ecg.getPvcPoslistStr()));
        vo.setArrestPoslist(JSON.parseArray(ecg.getArrestPoslistStr()));
        vo.setMissedPoslist(JSON.parseArray(ecg.getMissedPoslistStr()));
        vo.setInsertPvcPoslist(JSON.parseArray(ecg.getInsertPvcPoslistStr()));
        vo.setVtPoslist(JSON.parseArray(ecg.getVtPoslistStr()));
        vo.setBigeminyPoslist(JSON.parseArray(ecg.getBigeminyPoslistStr()));
        vo.setTrigeminyPoslist(JSON.parseArray(ecg.getTrigeminyPoslistStr()));
        vo.setRList(JSON.parseArray(ecg.getRListStr()));
        return vo;
    }

    public BaseResult selectPageGroup(Page page, String name) {
        //Integer stationId = stationService.getLoginUserStation();
        Integer stationId = null;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<EcgData> list = ecgDataMapper.selectPageGroup(name, stationId);
        List<EcgDataVO> voList = list.stream().map(ecgData -> entity2VO(ecgData)).collect(Collectors.toList());
        PageInfo<EcgDataVO> pageInfo = new PageInfo<>(voList);
        return BaseResult.ok(pageInfo);
    }

    public String getToken() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("appSecret", "972233c717cc17d23a3c");
        String request = HttpUtils.getRequest("http://203.195.168.139:8086/amsuAnalysis/user/auth-service/41c0df02b438ddaa47a2/auth", map);
        JSONObject jsonObject = JSON.parseObject(request);
        Map errDesc = (Map) jsonObject.get("errDesc");
        String token = (String) errDesc.get("token");
        Long expiration_time = Long.valueOf(errDesc.get("expiration_time").toString());
        RedisUtil.set("ecgToken", token, expiration_time - 1000l);
        return token;
    }

    public BaseResult selectPageByCustomerId(Page page, Integer customerId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<EcgData> list = ecgDataMapper.selectPageByCustomerId(customerId);
        List<EcgDataVO> voList = list.stream().map(ecgData -> entity2VO(ecgData)).collect(Collectors.toList());
        PageInfo<EcgDataVO> pageInfo = new PageInfo<>(voList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult selectById(Integer id) {
        EcgData ecgData = ecgDataMapper.selectById(id);
        return BaseResult.ok(entity2VO(ecgData));
    }

    public BaseResult selectLastByCustomerId(Integer customerId) {
        return BaseResult.ok(ecgDataMapper.selectLastByCustomerId(customerId));
    }
}
